const fs= require('fs');
const path= require('path');

// console.log(path.join(__dirname, '../public/upload/'));
// 文件上传
function fileUpload(file) {
    return new Promise((resolve, reject) => {
        const reader= fs.createReadStream(file.path);
        let filePath= path.join(__dirname, '../public/upload/');  // 要存储的文件目录
        let filenameArr= (file.name).split('.');
        let fileSuffix = filenameArr[filenameArr.length-1]; // 获取文件后缀
        let filename= Date.now() + '.' + fileSuffix;  // 重命名文件
        let fileResource = filePath + filename;  // 最终的文件路径
        if(!fs.existsSync(filePath)) { //判断public/upload文件夹是否存在，如果不存在就新建一个
            fs.mkdir(filePath, err=>{
                if(err) {
                    throw new Error(err);
                } else {
                    try {
                        let writer = fs.createWriteStream(fileResource);
                        reader.pipe(writer);
                        resolve({
                            status: 0,
                            filename: filename
                        })
                    } catch (e) {
                        reject({
                            status: 1,
                            msg: '文件创建失败'
                        });
                    }
                }
            })
        } else {
            try {
                let writer = fs.createWriteStream(fileResource);
                reader.pipe(writer);
                resolve({
                    status: 0,
                    filename: filename
                })
            } catch (e) {
                reject({
                    status: 1,
                    msg: '文件创建失败'
                });
            }
        }
    });
}

// 文件下载
function fileDownload(fileUrl) {

}


module.exports= {
    fileUpload,
    fileDownload
}
